import typeOfUtils from "./type-of-utils.js";
import NumberUtils from "./NumberUtils.js";

/**
 * 行等长 虚拟滚动
 * 计算父元素height，paddingTop，paddingBottom，
 * 使用： 父元素样式  virtualListUtils.showListClass()
 * 子元素样式： virtualListUtils.getItemStyle()
 * 显示的列表数据： virtualListUtils.showList()
 * 初始化： virtualListUtils.init(result, uni.upx2px(628), 10) // 这个可以动态调用
 */

class VirtualListUtils {
  _list = []
  _beginPos = 0
  _showLength = 0
  _paddingTop = 0
  _itemHeight = 0
  _maxBeginPos = 0
  _maxPaddinTop = 0
  _lastTime = new Date().getTime()
  _cacheTopNumber = 0
  showAgain = true
  _timer = null
  _domLoadAgain = false

  setBeginPos(position) {
    if (this._domLoadAgain) {
      this.offTimeSetShowAgain(500)
    }
    const time = new Date().getTime()
    if (time - this._lastTime > 16) {
      position -= (this._itemHeight * this._cacheTopNumber)
      this._setPaddingTop(position)
      let num = NumberUtils.toInt(this._paddingTop / this._itemHeight)
      if (num < 0) {
        this._beginPos = 0
      } else {
        if (num >= this._maxBeginPos) {
          num = this._maxBeginPos
        }
        this._beginPos = num
      }
      this._lastTime = time
    }
  }

  offTimeSetShowAgain(time = 500) {
    clearTimeout(this._timer)
    this._timer = null
    this._timer = setTimeout(() => {
      if (this._domLoadAgain) {
        this.showAgain = !this.showAgain
      }
    }, time)
  }

  _getOffsetY() {
    let num = this._paddingTop - (this._paddingTop % this._itemHeight)
    if (num < 0) {
      num = 0
    }
    return num
  }

  getItemStyle() {
    return {
      transform: `translateY(${this._getOffsetY()}px)`
    }
  }

  _setPaddingTop(val) {
    if (val <= 0) {
      this._paddingTop = 0
    } else {
      if (val >= this._maxPaddinTop) {
        val = this._maxPaddinTop
      }
      this._paddingTop = val
    }
  }

  showList() {
    if (typeOfUtils.isEmpty(this._list)) {
      return []
    }
    return this._list.slice(this._beginPos, this._beginPos + this._showLength)
  }

  _getHeight() {
    if (typeOfUtils.isEmpty(this._list)) {
      return 0
    }
    return this._itemHeight * this._list.length
  }

  showListClass() {
    const style = {
      height: '0px',
    }
    if (typeOfUtils.isEmpty(this._list)) {
      return style
    }
    style.height = this._getHeight() + 'px'
    return style
  }

  init(list = [], itemHeight = 100, showLength = 10, domLoadAgain = false) {
    if (typeOfUtils.isEmpty(list)) {
      this._list = []
      return
    }
    this._list = list
    this._itemHeight = itemHeight
    this._showLength = showLength
    if (list.length < showLength) {
      this._showLength = list.length
    }
    this._maxPaddinTop = this._getHeight() - this._showLength * this._itemHeight;
    this._maxBeginPos = this._list.length - this._showLength
    this._cacheTopNumber = NumberUtils.toInt(this._showLength / 3)
    this._domLoadAgain = domLoadAgain
  }
}

export default VirtualListUtils
